# -*- coding: utf-8 -*-
# @时间：2023/11/2 19:56
# @作者：CJiaの可乐哥
# @文件名：cj_jwt
# @软件：Pycharm2023
import jwt
import json
import datetime
from jwt import exceptions

from backend_v2.settings import SECRET_KEY
from django.core.cache import cache


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")
        else:
            return json.JSONEncoder.default(self, obj)


# JWT加密 =>> token
def create_token(payload, timeout=60):
    headers = {
        "type": "jwt",
        "alg": "HS256"
    }
    # 设置过期时间
    payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout)
    result = jwt.encode(payload=payload, key=SECRET_KEY, algorithm="HS256", headers=headers)
    # 缓存token
    cache.set(payload['username'] + str(payload['key']), result, timeout * 60)
    # 返回加密结果
    return result


# token =>> 用户信息
def parse_payload(token):
    # 自定义对象
    message = {"code": 0, "data": None, "msg": "操作成功"}
    try:
        userinfo = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        # 返回结果
        message['data'] = userinfo
    except exceptions.ExpiredSignatureError:
        message['code'] = -1
        message['msg'] = "token已过期"
    except jwt.DecodeError:
        message['code'] = -1
        message['msg'] = "token认证失败"
    except jwt.InvalidTokenError:
        message['code'] = -1
        message['msg'] = "非法的token"
    # 返回解密结果
    return message
